// pages/mydesign/mydesign.js
let app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        query: '',
        primary: '', // 主题色
        ossPath: app.globalData.ossPath,
        formData: {
            TeamNum: '',
            pageIndex: 1,
            pageSize: 10,
            productcategory: '',
            startTime: '',
            endTime: '',
            more: true
        },
        animationData: {}, // 动画
        animationData2: {},
        imgAnimation: {}, // 图片加载动画
        downMenu: false, // 下拉弹框
        menu: { // 筛选
            typeId: '',
            num: '',
            state: 0,
            time: 0,
            startTime: '',// 查询开始时间: default ''
            endTime: '',// 查询结束时间: default ''
        },
        designRecords: [], // 设计记录列表
        designIndex: 0, // 记录下标
        productCategories: [] , // 筛选产品
        designListRecord: [[],[]], // 设计
        designListHeight: [0,0],//
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //设置主题色
        if (app.globalData.primary) {
            this.setData({ primary: app.globalData.primary })
            app.usePrimary(app.globalData.primary)
        }
        this.data.formData.TeamNum = app.globalData.user.team
        wx.showLoading({
            title: '加载中',
        })
        this.getDesignRecords().then(data => {
            wx.hideLoading()
            this.data.designRecords = this.filterDesignList(data.Data)
            let list = this.data.designRecords.shift();
            this.data.designListRecord[0].push(list)
            const query = wx.createSelectorQuery()
            this.setData({
                query,
                designRecords: this.data.designRecords,
                designListRecord: this.data.designListRecord,
                designIndex: this.data.designIndex
            })
            
            this.test()
        })
        this.getProductCategories();

    },
    test() {
        if (!this.data.designRecords.length) {
            return;
        }
        setTimeout(() => {
            var query = this.data.query;
            query.select('#mydesign-list-one').boundingClientRect()
            query.select('#mydesign-list-two').boundingClientRect()
            query.exec((res) => {
                // console.log(res)
                let list = this.data.designRecords.shift();
                if (res[0].height <= res[1].height) {
                    this.data.designListRecord[0].push(list)

                } else {
                    this.data.designListRecord[1].push(list)
                }
                this.setData({
                    designListRecord: this.data.designListRecord
                })
                this.test();
            })
        }, 0)
    },
    getDesignRecords() { // 获取设计记录
        return new Promise(resolve => {
            let url = app.globalData.serverPath + '/SetUpTemplate';
            let form = '';
            for (var key in this.data.formData) {
                form += key + '=' + this.data.formData[key] + '&'
            }
            wx.request({
                url: url,
                method: 'POST',
                data: form,
                header: app.globalData.header,
                success: (res) => {
                    var data = res.data
                    resolve(data)
                },
                fail: err => resolve(false)
            })
        })
        

    },
    getProductCategories() { // 获取筛选分类
        wx.request({
            url: app.globalData.serverPath + '/designer/products',
            header: app.globalData.header,
            success: ({data}) => {
                this.setData({
                    productCategories: data
                })
            }
        })
    },
    filterProductData(data) { // 过滤筛选分类
        data.forEach((item, index) => {
            item.selected = false;
            if (!index) item.selected = true;
        })
    },
    filterDesignList(data) { // 过滤设计记录
        data.forEach((item, index) => {
            item.AddTime = item.AddTime.replace('T', " ")
            item.index = index;
            item.show = false;
        })
        return data;
    },
    setDownMenu: function (e) { // 显示下拉选择并动画
        let type = e.currentTarget.dataset.type
        if (type == '-1') return;
        this.setAnimation(type);

        //初始化动画
    },
    setAnimation: function(type) { // 设置动画
        var animation = wx.createAnimation({
            duration: 300,
            timingFunction: 'ease'
        })
        var animation2 = wx.createAnimation({
            duration: 300,
            timingFunction: 'ease'
        })

        if (type) {
            animation.translateY(-404).step()
            animation2.opacity(0).step()
            this.setData({
                downMenu: type,
                animationData: animation.export(),
                animationData2: animation2.export()
            })
            setTimeout(() => {
                animation.translateY(0).step()
                animation2.opacity(1).step()
                this.setData({
                    animationData: animation.export(),
                    animationData2: animation2.export()
                })
            }, 300)

        } else {
            animation.translateY(-404).step()
            animation2.opacity(0).step()
            this.setData({
                animationData: animation.export(),
                animationData2: animation2.export()
            })
            setTimeout(() => {
                this.setData({ downMenu: type })
            }, 300)
        }
    },
    selectMenu: function (e) { // 一级分类
        this.data.menu.left = e.currentTarget.dataset.sel;
        this.data.menu.num = e.currentTarget.dataset.num;
        this.setData({
            menu: this.data.menu
        })
    },
    selectMenuState: function (e) { // 选择状态
        this.data.menu.typeId = e.currentTarget.dataset.typeid;
        // console.log(this.data.menu)
        this.setData({
            menu: this.data.menu
        })
    },
    changeTime: function (e) { // 选择开始和结束时间
        this.data.menu.time = e.currentTarget.dataset.time;
        this.setData({
            menu: this.data.menu
        })
    },
    changeTimestart(e) { // 开始时间
        this.data.menu.startTime = e.detail.value
        this.setData({
            menu: this.data.menu
        })
    },
    changeTimeend(e) { // 结束时间
        this.data.menu.endTime = e.detail.value
        this.setData({
            menu: this.data.menu
        })
    },

    setDesignListLayout: function(index, height, i) { // 瀑布流健在
        this.data.designListHeight[index] += height

        this.setData({ designListOneHeight: this.data.designListHeight })

        let list = this.data.designRecords[this.data.designIndex];
        this.data.designIndex++;
        if (this.data.designIndex >= this.data.designRecords.length) {
            console.log(this.data.designRecords)
            return;
        }

        if (this.data.designListHeight[0] <= this.data.designListHeight[1]) {
            this.data.designListRecord[0].push(list)
            this.setData({
                designListRecord: this.data.designListRecord,
                designIndex: this.data.designIndex
            })
        } else {
            this.data.designListRecord[1].push(list)
            this.setData({
                designListRecord: this.data.designListRecord,
                designIndex: this.data.designIndex
            })
        }

    },
    imageLoaded: function ({ detail, currentTarget }) {// 图片加载完成计算
        var index = currentTarget.dataset.index;
        var i = currentTarget.dataset.i;
        this.setDesignListLayout(index, detail.height, i);
        
    },
    deleteDesign: function(e) {// 删除设计记录
        let index = e.currentTarget.dataset.index,
            i = e.currentTarget.dataset.i;
        var num = this.data.designListRecord[index][i].DocumentNumber;
        // console.log(num)
        var that = this;
        wx.showModal({
            title: '确认删除该模板吗？',
            content: '删除后不可恢复',
            success: (res) => {
                if (res.confirm) {
                    let data = `DocumentNumber=${num}&TeamNum=${app.globalData.user.team}`
                    // console.log('用户点击确定', data)
                    wx.request({
                        url: app.globalData.serverPath + '/TeamTemplate',
                        method: 'delete',
                        header: app.globalData.header,
                        data: data,
                        success: ({ data }) => {
                            if(data == 'Success') {
                                that.data.designListRecord[index].splice(i, 1)
                                that.setData({
                                    designListRecord: that.data.designListRecord
                                })
                            }
                        }
                    })
                } 
            }
        })
    },
    gotoDesign: function(e) { //去设计器
        app.checkedUserInfo().then(ok =>{
            if (!ok) return;
            var d = e.currentTarget.dataset.d;
            wx.setStorageSync('d', d)
            wx.setStorageSync('m', 1)
            // var data = '?d=' + d + '&team=' + app.globalData.user.team + '&m=1' + '&token=' + app.globalData.header.token
            wx.navigateTo({
                url: '../design/design',
            })

        })
    },
    screenDesign: function () { // 筛选记录
        console.log(this.data.menu , this.data.formData)
        this.data.formData.pageIndex = 1;
        this.data.formData.productcategory = this.data.menu.num;
        if (this.data.menu.startTime && this.data.menu.endTime) {
            this.data.formData.startTime = this.data.menu.startTime + ' 00:00:00';
            this.data.formData.endTime = this.data.menu.endTime + ' 00:00:00';

        }
        this.setData({
            formData: this.data.formData
        })
        wx.showLoading({
            title: '加载中',
        })
        this.getDesignRecords().then(data => {
            wx.hideLoading()
            this.data.designListRecord =  [[], []]
            this.data.designRecords = this.filterDesignList(data.Data)
            let list = this.data.designRecords.shift();
            this.data.designListRecord[0].push(list)
            const query = wx.createSelectorQuery()
            console.log(this.data.designRecords)
            this.setData({
                query,
                designRecords: this.data.designRecords,
                designListRecord: this.data.designListRecord,
                designIndex: this.data.designIndex
            })

            this.test()
        })
        this.setAnimation(false)
    },
    reset: function () { //重置
        this.data.formData.pageIndex = 1
        this.data.formData.productcategory = ''
        this.data.formData.startTime = ''
        this.data.formData.endTime = ''
        this.data.menu = {
            typeId: '',
            num: '',
            state: 0,
            time: 0,
            startTime: '',// 查询开始时间: default ''
            endTime: '',// 查询结束时间: default ''
        }
        this.setData({
            formData: this.data.formData,
            menu: this.data.menu
        })
        wx.showLoading({
            title: '加载中',
        })
        this.getDesignRecords().then(data => {
            wx.hideLoading()
            this.data.designListRecord = [[], []]
            this.data.designRecords = this.filterDesignList(data.Data)
            let list = this.data.designRecords.shift();
            this.data.designListRecord[0].push(list)
            const query = wx.createSelectorQuery()
            console.log(this.data.designRecords)
            this.setData({
                query,
                designRecords: this.data.designRecords,
                designListRecord: this.data.designListRecord,
                designIndex: this.data.designIndex
            })

            this.test()
        })
        this.setAnimation(false)
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        if (!this.data.formData.more) return;
        // console.log(123)
        this.data.formData.pageIndex++
        this.data.formData.more = false
        this.setData({
            formData: this.data.formData
        })
        
        this.getDesignRecords().then(data => {
            this.data.formData.more = true
            this.data.designRecords = this.filterDesignList(data.Data)
            let list = this.data.designRecords.shift();
            this.data.designListRecord[0].push(list)
            const query = wx.createSelectorQuery()
            this.setData({
                query,
                designRecords: this.data.designRecords,
                designListRecord: this.data.designListRecord,
                designIndex: this.data.designIndex,
                formData: this.data.formData
            })

            this.test()
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})